/*
* 1、serviceId是已知的，不需要调用getBLEDeviceServices
* 2、Characteristic是已知的，不需要调用getBLEDeviceCharacteristics
* 3、iOS平台上后续对特征值的read、write、notify，
* 由于系统需要获取特征值实例，传入的 serviceId 与 characteristicId
* 必须由 getBLEDeviceServices 与 getBLEDeviceCharacteristics 中获取到后才能使用。
* 建议双平台统一在建立链接后先执行 getBLEDeviceServices 与 getBLEDeviceCharacteristics 后
* 再进行与蓝牙设备的数据交互
*
* */
const {
  serviceId, discovery,closeCube,connect
} = require('../../utils/bluetooth');
const {ab2hex,cubeIsOnline,goToDeviceInfo,getPageInstance,whenConnectedSaveInfo,
  log,jump,getCubeName,json2string,setCubeInfo} = require('../../utils/util');
const {Event} = require('../../utils/constant');

const app = getApp();

Page({
  data: {
    ignoreMatchedAmount:3,//iPhone中，1、蓝牙配对cube成功 2、关闭连接 3、再次配对同一cube，第一次的flag为1（bug）
    matchStatus:2//配对中2，失败0，成功1
  },
  onLaunch: function () {
  },
  onLoad:function(){

    const that = this;
    this.scan = this.scan.bind(this);
    this.findCorrectDevice = this.findCorrectDevice.bind(this);

    app.event.on(Event.BluetoothAdapterStateChange, that.BluetoothAdapterStateChangeHandler, that);

    const online = cubeIsOnline();
    if(online){
      //当前cube必离线了，断开其它cube。
      closeCube(function () {
        that.scan();
      })
    }else{
      that.scan();
    }


  },
  onShow: function () {

  },
  onUnload: function () {
    wx.stopBluetoothDevicesDiscovery();
    app.event.off(Event.BluetoothAdapterStateChange, this.BluetoothAdapterStateChangeHandler);
  },
  BluetoothAdapterStateChangeHandler: function (available) {

    this.setData({matchStatus:2});

    if (available) {
      this.scan();
    } else {
      this.setData({matchStatus: 0});
    }
  },
  findCorrectDevice: function (devices, cubeKeysArr) {
    try {
      const dv = devices.devices[0];
      let ignoreMatchedAmount = this.data.ignoreMatchedAmount;

      var {deviceId, advertisData, localName, name} = dv; //deviceId是mac地址，cube重启后可能会变
      var cubeKey;
      //flag=1时，cube才在配对模式中
      var flag = parseInt(ab2hex(advertisData).substr(-2, 2));
      //同一个cube会多次被发现，即多次进入该函数
      const ad = ab2hex(advertisData);
      cubeKey = ad.substr(0, 20);
      var productId = ad.substring(6, 10);//据此判断cube是否支持甲醛检测
      var serialNumber = ad.substring(0, 20); //序列号，唯一
      if (cubeKeysArr.length === 0/*只允许配对一个cube*/ && cubeKeysArr.indexOf(cubeKey) === -1 && flag === 1) {
        if(ignoreMatchedAmount > 0){
          flag = 0;
          this.setData({ignoreMatchedAmount:ignoreMatchedAmount-1});
          log(`ignoreMatchedAmount:${this.data.ignoreMatchedAmount}`);
        }else{
          cubeKeysArr.push(cubeKey);
        }
      } else {
        return false;
      }
    } catch (e) {
      flag = 0;
    }
    if (!localName || flag !== 1) {
      return false;//important
    } else {
      return {deviceId, localName, name, productId, serialNumber};
    }
  },
  scan: function () {
    const that = this;

    this.setData({matchStatus:2});

    let cubeKeysArr = [];

    discovery(function (devices)/*新搜索到的设备列表*/ {
      const dv = that.findCorrectDevice(devices, cubeKeysArr);
      log(`dv.......${json2string(dv)}`);
      if (dv) {
        const {deviceId, name,localName, productId,serialNumber} = dv;
        // const cubeName = getCubeName({serialNumber});

        wx.stopBluetoothDevicesDiscovery({
          complete: function () {
            //stopBluetoothDevicesDiscovery成功后，再调用connect，非常重要。
            log(`found device: deviceId=${deviceId}, serialNumberFound=${serialNumber}`);
            log(`willConnect device: deviceId=${deviceId}, serialNumber=${serialNumber}`);
            connect({
              deviceId,
              connectSuccess: function () {
                log(`serialNumber:${serialNumber},deviceId:${deviceId} connectSuccess`);
                whenConnectedSaveInfo({serialNumber,cubeName:getCubeName({serialNumber})});
                // setCubeInfo({serialNumber, info: {deviceId, cubeName, matchStatus: 3}});
                setCubeInfo({serialNumber, info: {deviceId, cubeName:getCubeName({serialNumber})}});
                that.setData({matchStatus:1});
                setTimeout(function () {
                  goToDeviceInfo({serialNumber,needConnect:0})
                },2500);
              },
              fail: function () {
                that.setData({matchStatus:0});
              },
              complete: function () {
                wx.setStorageSync('autoReconnect', 1);
              }
            });

          }
        });
      } else {

      }
    })
  },
  hintTap:function () {
    jump({pageName:'cubeErrorHint',type:1});
  },
  rematch:function () {
    this.scan();
  }
});


